package com.kenyi.co.common.ui;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.kenyi.co.GlideApp;
import com.kenyi.co.MainActivity;
import com.kenyi.co.R;
import com.kenyi.co.common.utils.DialogWhiteUtils;
import com.kenyi.co.common.utils.X5WebView;
import com.kenyi.co.ui.StartActivity;
import com.kenyi.co.ui.me.ui.MeFavActivity;
import com.kenyi.co.utils.CommonUtils;
import com.kenyi.co.utils.ConnectNet;
import com.kenyi.co.utils.GlideRoundedCorners;
import com.kenyi.co.utils.LogU;
import com.kenyi.co.utils.SharepUtils;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient.CustomViewCallback;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebSettings.LayoutAlgorithm;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.umeng.analytics.MobclickAgent;

import static android.view.KeyEvent.KEYCODE_BACK;

public class WebActivity extends BaseActivity implements View.OnClickListener {
    private X5WebView mWebView;
    private ViewGroup mViewParent;
    private String mHomeUrl, is_main = "0";
    private static final String TAG = "Othersx5WebActivity";

    private String cUrl;
    private boolean is_stop = true;
    private boolean is_re = true;//跳开页面是否刷新

    private FrameLayout webParentView;
    private RelativeLayout re_top_title;

    private String title;

    private TextView tv_home_title;
    private boolean is_reload = false;//是否重新加载
    private ImageView iv_web_back, iv_ceping_home_share, tv_web_off;
    private boolean Progressflag = false;
    private View mErrorView; //
    private Button bt_main_again;
    private TextView tv_loading;
    private ImageView iv_web_load;

    private LinearLayout li_ziliao_home_shoucang;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (intent != null) {
            try {
                if (bundle != null && bundle.containsKey("title")) {
                    title = bundle.getString("title");
                }
                if (bundle != null && bundle.containsKey("URL")) {

                    mHomeUrl = bundle.getString("URL");
                }
                if (bundle != null && bundle.containsKey("is_main")) {
                    is_main = bundle.getString("is_main");

                }

            } catch (Exception e) {
            }
        }

        try {
            if (Integer.parseInt(Build.VERSION.SDK) >= 11) {
                getWindow()
                        .setFlags(
                                android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                                android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
            }
        } catch (Exception e) {
        }
        setContentView(R.layout.activity_main_web);
        mViewParent = (ViewGroup) findViewById(R.id.webView1);
        iv_web_load = findViewById(R.id.iv_web_load);


        re_top_title = findViewById(R.id.top);

        initView();
        init();
        initErrorPage();//初始化自定义页面
        tv_loading = mErrorView.findViewById(R.id.tv_loading);
        if (!ConnectNet.isNetworkReachable(WebActivity.this)) {
            showErrorPage();

            tv_loading.setText("网络中断请检查网络");
            return;
        }

    }

    // 初始化标题的按钮
    private void initView() {
        tv_home_title = (TextView) findViewById(R.id.tv_home_title);
        iv_web_back = findViewById(R.id.iv_web_back);
        iv_ceping_home_share = findViewById(R.id.iv_ceping_home_share);
        tv_web_off = findViewById(R.id.tv_web_off);
        li_ziliao_home_shoucang = findViewById(R.id.li_ziliao_home_shoucang);
        iv_ceping_home_share.setOnClickListener(this);
        li_ziliao_home_shoucang.setOnClickListener(this);
        iv_web_back.setOnClickListener(this);
        tv_web_off.setOnClickListener(this);
        mViewParent.setVisibility(View.GONE);
        iv_web_load.setVisibility(View.VISIBLE);

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        reLoadWeb();
        is_stop = true;
        is_re = true;
    }

    private void init() {

        mWebView = new X5WebView(this, null);

        mViewParent.addView(mWebView, new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.FILL_PARENT,
                FrameLayout.LayoutParams.FILL_PARENT));


        webParentView = (FrameLayout) mWebView.getParent(); //获取父容器
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onJsConfirm(WebView arg0, String arg1, String arg2,
                                       JsResult arg3) {
                return super.onJsConfirm(arg0, arg1, arg2, arg3);
            }

            View myVideoView;
            View myNormalView;
            CustomViewCallback callback;

            /**
             * 全屏播放配置
             */
            @Override
            public void onShowCustomView(View view,
                                         CustomViewCallback customViewCallback) {
                FrameLayout normalView = (FrameLayout) findViewById(R.id.web_filechooser);
                ViewGroup viewGroup = (ViewGroup) normalView.getParent();
                viewGroup.removeView(normalView);
                viewGroup.addView(view);
                myVideoView = view;
                myNormalView = normalView;
                callback = customViewCallback;
            }

            @Override
            public void onHideCustomView() {
                if (callback != null) {
                    callback.onCustomViewHidden();
                    callback = null;
                }
                if (myVideoView != null) {
                    ViewGroup viewGroup = (ViewGroup) myVideoView.getParent();
                    viewGroup.removeView(myVideoView);
                    viewGroup.addView(myNormalView);
                }
            }

            @Override
            public boolean onJsAlert(WebView arg0, String arg1, String arg2,
                                     JsResult arg3) {
                /**
                 * 这里写入你自定义的window alert
                 */
                return super.onJsAlert(null, arg1, arg2, arg3);
            }

            @Override
            public void onReceivedTitle(WebView webView, String s) {
                super.onReceivedTitle(webView, s);

                tv_home_title.setText("" + s);

            }

            @Override
            public void onProgressChanged(WebView webView, int i) {
                super.onProgressChanged(webView, i);
                if (i == 100) {
                    mViewParent.setVisibility(View.VISIBLE);
                    iv_web_load.setVisibility(View.GONE);

                }

                if (i > 10) {
                    Progressflag = true;
                }
            }


        });

        WebSettings webSetting = mWebView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        webSetting.setAppCacheEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .getPath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        webSetting.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);


        cUrl = getUrlInfo();
        mWebView.loadUrl(cUrl);
        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().sync();

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                //6.0以下执行
                showErrorPage();
            }

            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
                if (sslError.getPrimaryError() == android.net.http.SslError.SSL_DATE_INVALID
                        || sslError.getPrimaryError() == android.net.http.SslError.SSL_EXPIRED
                        || sslError.getPrimaryError() == android.net.http.SslError.SSL_INVALID
                        || sslError.getPrimaryError() == android.net.http.SslError.SSL_UNTRUSTED) {
                    sslErrorHandler.proceed();
                } else {
                    sslErrorHandler.cancel();
                }
                super.onReceivedSslError(webView, sslErrorHandler, sslError);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                iv_web_load.setVisibility(View.GONE);
                mViewParent.setVisibility(View.VISIBLE);

            }

        });
    }


    @Override
    public void onResume() {
        super.onResume();
        try {
            if (mWebView != null) {
                mWebView.onResume();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


        MobclickAgent.onPageStart("通用WebView");
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {

        MobclickAgent.onPageEnd("通用WebView");
        if (is_stop) {
            if (is_re) {


                mWebView.stopLoading();
                mWebView.reload();
                try {
                    if (mWebView != null) {
                        mWebView.onPause();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        MobclickAgent.onPause(this);
        super.onPause();
    }

    @Override
    protected void onDestroy() {

        if (mWebView != null) {
            mWebView.stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            mWebView.getSettings().setJavaScriptEnabled(false);
            mWebView.clearHistory();
            mWebView.removeAllViews();
            try {
                mWebView.destroy();
                mWebView = null;
            } catch (Throwable ex) {

            }
        }


        super.onDestroy();
    }


    @Override
    protected void onNewIntent(Intent intent) {
        if (intent == null || mWebView == null || intent.getData() == null)
            return;
        mWebView.loadUrl(intent.getData().toString());
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.bt_main_again:

                reLoadWeb();
                is_reload = true;
                break;

            case R.id.iv_web_back:

                if ("1".equals(is_main)) {

                    gotoMainActivity();
                } else {
                    if (mWebView.canGoBack()) {
                        mWebView.goBack();
                    } else {
                        finish();
                    }
                }

                break;
            case R.id.tv_web_off:

                finish();

                break;


        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KEYCODE_BACK) && mWebView.canGoBack()) {

            if ("1".equals(is_main)) {
                gotoMainActivity();
            }
            return true;
        } else if ((keyCode == KEYCODE_BACK) && "1".equals(is_main)) {

            gotoMainActivity();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void gotoMainActivity() {

        if ("1".equals(SharepUtils.getString_info(WebActivity.this, SharepUtils.USER_LOGIN_ONE))) {
            Intent intent2 = new Intent();
            intent2.setClass(WebActivity.this, MainActivity.class);
            startActivity(intent2);
            overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
        } else {
            Intent intent2 = new Intent();
            intent2.setClass(WebActivity.this, MeFavActivity.class);
            Bundle bundlelogin = new Bundle();
            bundlelogin.putString("isfinish", "1");
            intent2.putExtras(bundlelogin);
            startActivity(intent2);
        }
        finish();
    }

    /**
     * 显示自定义错误提示页面，用一个View覆盖在WebView
     */
    private void showSuccessPage() {
        webParentView.removeAllViews(); //移除加载网页错误时，默认的提示信息
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        webParentView.addView(mWebView, 0, layoutParams); //添加自定义的错误提示的View
    }

    /**
     * 显示自定义错误提示页面，用一个View覆盖在WebView
     */
    private void showErrorPage() {
        webParentView.removeAllViews(); //移除加载网页错误时，默认的提示信息
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        webParentView.addView(mErrorView, 0, layoutParams); //添加自定义的错误提示的View
    }

    /***
     * 显示加载失败时自定义的网页
     */
    private void initErrorPage() {
        if (mErrorView == null) {
            mErrorView = View.inflate(this, R.layout.main_loading, null);
            bt_main_again = mErrorView.findViewById(R.id.bt_main_again);
            bt_main_again.setOnClickListener(this);
        }
    }

    /**
     * 重新加载网页
     */
    private void reLoadWeb() {
        if (is_reload) {
            if (ConnectNet.isNetworkReachable(WebActivity.this)) {

                is_reload = false;
                cUrl = getUrlInfo();
                mWebView.loadUrl(cUrl);
                showSuccessPage();
            }
        }
    }

    /**
     * 重置URL
     */
    private String getUrlInfo() {
        String Lurl;
        if (mHomeUrl.indexOf("?") == -1) {
//            Lurl = mHomeUrl + "?uid="
//                    + SharepUtils.getUserUSER_ID(this) + "&key="
//                    + SharepUtils.getUserUSER_KEY(this) + "&version=1&code_version=" + Util.getVersionCode(this);
////                    +"&is_from=special_app_edition";
        } else {
//            Lurl = mHomeUrl + "&uid="
//                    + SharepUtils.getUserUSER_ID(this) + "&key="
//                    + SharepUtils.getUserUSER_KEY(this) + "&version=1&code_version=" + Util.getVersionCode(this);
////                    +"&is_from=special_app_edition";
        }
        mHomeUrl = mHomeUrl;
        return mHomeUrl;

    }


}
